package com.carboy.launch;

import android.content.Context;
import android.util.Log;

import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SynthesizerListener;
import com.iflytek.cloud.util.ResourceUtil;
import com.iflytek.cloud.util.ResourceUtil.RESOURCE_TYPE;


public class IflyTTS {

	private static String TAG = "IflyTTS";

	public IflyTTS() {

	}

	private static SpeechSynthesizer mTts = null;

	public static void initIflyTTS(Context mContext, InitListener initListener) {

		mTts = SpeechSynthesizer.getSynthesizer();
		if (mTts == null) {
			mTts = SpeechSynthesizer.createSynthesizer(mContext, initListener);
		}
//		setParam(mContext);
	}

	public static void beginIflyTTS(Context mContext, String msg,
			SynthesizerListener synListener) {
		setParam(mContext);
		Log.i("<--->", "播报语音：" + msg);
		int code = mTts.startSpeaking(msg, synListener);
		if (code != ErrorCode.SUCCESS) {
			Log.i("<--->", "语音合成失败,错误码:" + code);
		} else {

		}

	}

	/**
	 * 参数设置
	 * 
	 * @param param
	 * @return
	 */
	private static void setParam(Context context) {
		// 清空参数
		mTts.setParameter(SpeechConstant.PARAMS, null);
		// 设置合成

		// 设置使用本地引擎
		mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_LOCAL);
		// 设置发音人资源路径
		mTts.setParameter(ResourceUtil.TTS_RES_PATH, getResourcePath(context));
		// 设置发音人
		mTts.setParameter(SpeechConstant.VOICE_NAME, "xiaoyan");

		// 设置语速
		mTts.setParameter(SpeechConstant.SPEED, "50");

		// 设置是否会话过程中暂停后台音乐播放
		mTts.setParameter(SpeechConstant.KEY_REQUEST_FOCUS, "1");

		// 设置音调
		mTts.setParameter(SpeechConstant.PITCH, "50");

		// 设置音量
		mTts.setParameter(SpeechConstant.VOLUME, "80");

		// 设置播放器音频流类型
		mTts.setParameter(SpeechConstant.STREAM_TYPE, "3");
	}

	// 获取发音人资源路径
	private static String getResourcePath(Context context) {
		StringBuffer tempBuffer = new StringBuffer();
		// 合成通用资源
		tempBuffer.append(ResourceUtil.generateResourcePath(context,
				RESOURCE_TYPE.assets, "tts/common.jet"));
		tempBuffer.append(";");
		// 发音人资源
		tempBuffer.append(ResourceUtil.generateResourcePath(context,
				RESOURCE_TYPE.assets, "tts/xiaoyan.jet"));
		return tempBuffer.toString();
	}

	public static boolean isSpeaking() {
		if (mTts != null) {
			return mTts.isSpeaking();
		} else {
			return false;
		}
	}

	public static void stopSpeaking() {
		if (mTts != null && mTts.isSpeaking()) {
			Log.i("<--->", "...停止播报....");
			mTts.stopSpeaking();
		}
	}

	public static void destroy() {
		if (mTts != null)
			mTts.destroy();
	}

}
